using System.Threading.Tasks;
using Admin.NET.Core;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Furion.FriendlyException;
using Microsoft.AspNetCore.Mvc;

namespace Admin.NET.Application.Service.Api;

[ApiDescriptionSettings(new string[] { "业务应用" }, Order = 100)]
public class AppMeterUserAuthService : IDynamicApiController, ITransient, IPrivateDependency
{
	private readonly UserManager _userManager;

	private readonly SqlSugarRepository<Room> _repRoom;

	private readonly SqlSugarRepository<ElectricMeter> _repEle;

	private readonly SqlSugarRepository<Owner> _repowner;

	public AppMeterUserAuthService(UserManager userManager, SqlSugarRepository<ElectricMeter> repEle, SqlSugarRepository<Room> repRoom, SqlSugarRepository<Owner> repowne)
	{
		_repEle = repEle;
		_repowner = repowne;
		_repRoom = repRoom;
		_userManager = userManager;
	}

	/// <summary>
	/// 获取用户的权限信息 0是物业未添加表  1是电表未绑定房间 2当前电表已绑定房间 3当前电表绑定到别人账号房间
	/// </summary>
	/// <param name="id"></param>
	/// <returns></returns>
	[HttpGet("/appmeteruserauth/owner")]
	public async Task<int> GetOwnerAuth(string id)
	{
		if (string.IsNullOrEmpty(id))
		{
			throw Oops.Bah("设备编号不能为空");
		}
		ElectricMeter device = await (from u in _repEle.AsQueryable()
			where u.Sn == id
			select u).FirstAsync();
		if (device == null)
		{
			return 0;
		}
		if (!device.RoomId.HasValue)
		{
			return 1;
		}
		Room room = await (from u in _repRoom.AsQueryable()
			where (long?)u.Id == device.RoomId
			select u).FirstAsync();
		if (room == null)
		{
			throw Oops.Bah("当前设备异常，请联系管理员");
		}
		if (room.OwnerId == _userManager.UserId)
		{
			return 2;
		}
		return 3;
	}

	/// <summary>
	/// 获取出租房电表权限 0是物业未添加表  1是已经添加表
	/// </summary>
	/// <param name="id"></param>
	/// <returns></returns>
	[HttpGet("/appmeteruserauth/user")]
	public async Task<int> GetUserAuth(string id)
	{
		if (string.IsNullOrEmpty(id))
		{
			throw Oops.Bah("设备编号不能为空");
		}
		if (await (from u in _repEle.AsQueryable()
			where u.Sn == id
			select u).FirstAsync() == null)
		{
			return 0;
		}
		return 1;
	}
}
